package com.opencee.cloud.msg.service.impl.email;

import com.opencee.cloud.msg.api.vo.params.EmailTextParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * @author yadu
 */
@Component
@Slf4j
public class EmailSenderServiceImpl {

    /**
     * 发送邮件
     */
    public void sendSimpleMail(JavaMailSenderImpl javaMailSender, EmailTextParams params) throws Exception {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(params.getTo().toArray(new String[]{}));
        helper.setFrom(javaMailSender.getUsername());
        helper.setSubject(params.getSubject());
        helper.setText(params.getContent(), true);
        this.addAttachment(helper, params);
        javaMailSender.send(message);
        log.debug("发送邮箱完成");
    }

    private void addAttachment(MimeMessageHelper helper, EmailTextParams params) throws MessagingException, IOException {
        if (params.getAttachments() != null && !params.getAttachments().isEmpty()) {
            for (Map<String, String> fileMap : params.getAttachments()) {
                String filePath = fileMap.get("filePath");
                String originalFilename = fileMap.get("originalFilename");
                File file = new File(filePath);
                helper.addAttachment(originalFilename, file);
            }
        }
    }


}
